#include <iostream>
#include <atomic>
#include <thread>
#include <vector>

std::atomic<bool> ready(false);
std::atomic_flag winner = ATOMIC_FLAG_INIT;

void countlm(int id)
{
    while(!ready){ 
        //当前线程放弃执行，让操作系统调度另一线程继续执行
        std::this_thread::yield();
        std::cout<<"this is thread: "<<id<<std::endl;
    } //wait for the ready signal

    
    std::cout<<"thread "<< id <<"start " <<std::endl;
    for(volatile int i = 0; i < 1000000; ++i){} //go!,count to 1 million
    if(!winner.test_and_set())
    {
        std::cout<< "thread #" << id << "won!" << std::endl;
    }
}
int main()
{

    std::vector<std::thread> threads;
    std::cout<<"spawning 10 threads that count to 1 million..."<<std::endl;
    for(int i=1; i<=10; ++i)
    {
        //std::cout<<"thread "<< i <<"start " <<std::endl;
        threads.push_back(std::thread(countlm,i));
    }
    ready=true;

    for(auto& th: threads)
        th.join();

    return 0;
}

